<template>
	<div class="app-container">
		<el-card class="card-container">
			<div slot="header" class="card-header">
				<span>设备统计</span>
			</div>

		<!-- 统计卡片 -->
		<div class="card-box">
			<el-card class="box-card">
				<div slot="header" class="card-header">
					<span>设备总数</span>
				</div>
				<div class="num-container">
					<span class="num-font">{{ deviceTotal }}</span>
				</div>
			</el-card>

			<el-card class="box-card">
				<div slot="header" class="card-header">
					<span>正常设备</span>
				</div>
				<div class="num-container">
					<span class="num-font green">
						{{ deviceNormal }} ({{ deviceNormalRate }}%)
					</span>
				</div>
			</el-card>

			<el-card class="box-card">
				<div slot="header" class="card-header">
					<span>维修设备</span>
				</div>
				<div class="num-container">
					<span class="num-font orange">
						{{ deviceMaintenance }} ({{ deviceMaintenanceRate }}%)
					</span>
				</div>
			</el-card>

			<el-card class="box-card">
				<div slot="header" class="card-header">
					<span>报废设备</span>
				</div>
				<div class="num-container">
					<span class="num-font red">
						{{ deviceScrapped }} ({{ deviceScrappedRate }}%)
					</span>
				</div>
			</el-card>
		</div>

		<!-- 设备类型统计图表 -->
		<div class="chart-container">
			<el-card class="chart-card">
				<div slot="header" class="card-header">
					<span>设备类型分布</span>
				</div>
				<div class="chart-box">
					<el-row :gutter="20">
						<el-col :span="16">
							<div id="deviceTypeChart" class="chart"></div>
						</el-col>
						<el-col :span="8">
							<el-table :data="deviceTypeList" style="width: 100%">
								<el-table-column prop="typeName" label="设备类型"></el-table-column>
								<el-table-column prop="count" label="数量"></el-table-column>
								<el-table-column prop="rate" label="占比"></el-table-column>
							</el-table>
						</el-col>
					</el-row>
				</div>
			</el-card>
		</div>

		<!-- 设备状态统计图表 -->
		<div class="chart-container">
			<el-card class="chart-card">
				<div slot="header" class="card-header">
					<span>设备状态分布</span>
				</div>
				<div class="chart-box">
					<div id="deviceStatusChart" class="chart"></div>
				</div>
			</el-card>
		</div>

		<!-- 设备列表 -->
		<div class="table-container">
			<el-card class="table-card">
				<div slot="header" class="card-header">
					<span>设备详情列表</span>
				</div>
				<el-table
						:data="deviceList"
						style="width: 100%"
						border
						stripe>
					<el-table-column prop="id" label="设备ID"></el-table-column>
				<el-table-column prop="deviceCode" label="设备编号"></el-table-column>
				<el-table-column prop="deviceName" label="设备名称"></el-table-column>
				<el-table-column prop="deviceType" label="设备类型">
					<template slot-scope="scope">
						{{ scope.row.deviceType || '-' }}
					</template>
				</el-table-column>
				<el-table-column prop="location" label="位置"></el-table-column>
				<el-table-column prop="installDate" label="安装日期">
					<template slot-scope="scope">
						{{ scope.row.installDate ? new Date(scope.row.installDate).toLocaleDateString() : '-' }}
					</template>
				</el-table-column>
					<el-table-column prop="status" label="设备状态">
						<template slot-scope="scope">
							<el-tag size="small" type="success" v-if="scope.row.status === 1">正常</el-tag>
							<el-tag size="small" type="warning" v-else-if="scope.row.status === 2">维修</el-tag>
							<el-tag size="small" type="danger" v-else-if="scope.row.status === 3">报废</el-tag>
							<el-tag size="small" type="warning" v-else>{{ scope.row.status || '-' }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="description" label="描述">
						<template slot-scope="scope">
							{{ scope.row.description || '-' }}
						</template>
					</el-table-column>
				</el-table>
				<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						layout="total, sizes, prev, pager, next, jumper"
						:page-sizes="[10, 20, 50, 100]"
						:current-page="current"
						:page-size="size"
						:total="deviceTotal">
				</el-pagination>
			</el-card>
		</div>
		</el-card>
	</div>
</template>

<script>
	import deviceApi from '@/api/device.js'
import statisticsApi from '@/api/data-statistics.js'
	export default {
		name: "DeviceStatistics",
		data() {
				return {
					total: 0,
					page_size: 10,
					page_num: 1,
					// 分页组件使用的变量
					current: 1,
					size: 10,

					// 统计数据
				deviceTotal: 0,
				deviceNormal: 0,
				deviceMaintenance: 0,
				deviceScrapped: 0,
				deviceNormalRate: 0,
				deviceMaintenanceRate: 0,
				deviceScrappedRate: 0,

				// 图表数据
				deviceTypeList: [],
				deviceStatusList: [],

				// 设备列表
				deviceList: [],

				// 图表实例
				deviceTypeChart: null,
				deviceStatusChart: null
			}
		},
		created() {
			this.getDeviceStatistics()
			this.getDeviceList()
		},
		mounted() {
			// 初始化图表
			setTimeout(() => {
				this.initDeviceTypeChart()
				this.initDeviceStatusChart()
			}, 100)
		},
		beforeDestroy() {
			// 销毁图表
			if (this.deviceTypeChart) {
				this.deviceTypeChart.dispose()
			}
			if (this.deviceStatusChart) {
				this.deviceStatusChart.dispose()
			}
		},
		watch: {
			deviceTypeList: {
				deep: true,
				handler() {
					this.updateDeviceTypeChart()
				}
			},
			deviceStatusList: {
				deep: true,
				handler() {
					this.updateDeviceStatusChart()
				}
			}
		},
		methods: {
			handleSizeChange(val) {
				this.size = val
				this.getDeviceList()
			},
			handleCurrentChange(val) {
				this.current = val
				this.getDeviceList()
			},

			// 获取设备统计数据
		getDeviceStatistics() {
			// 使用后端提供的统计接口
			statisticsApi.deviceStatistics().then(res => {
				try {
					if (res && res.code === 200 && res.data) {
						const stats = res.data
						
						// 设置状态统计数据
							this.deviceNormal = stats.onlineDevices || 0
							this.deviceMaintenance = stats.abnormalDevices || 0
							this.deviceScrapped = stats.offlineDevices || 0
						
						// 计算设备总数
							this.deviceTotal = this.deviceNormal + this.deviceMaintenance + this.deviceScrapped
						
						// 计算百分比
							this.deviceNormalRate = this.deviceTotal > 0 ? Math.round((this.deviceNormal / this.deviceTotal) * 100) : 0
							this.deviceMaintenanceRate = this.deviceTotal > 0 ? Math.round((this.deviceMaintenance / this.deviceTotal) * 100) : 0
							this.deviceScrappedRate = this.deviceTotal > 0 ? Math.round((this.deviceScrapped / this.deviceTotal) * 100) : 0
						
						// 更新状态列表数据
							this.deviceStatusList = [
								{ statusName: '正常', count: this.deviceNormal },
								{ statusName: '维修', count: this.deviceMaintenance },
								{ statusName: '报废', count: this.deviceScrapped }
							]
						
						// 由于后端没有提供设备类型统计，我们仍需获取设备列表来进行类型统计
						this.getDeviceTypeStatistics()
					} else {
						this.resetStatistics()
					}
				} catch (error) {
					console.error('处理设备统计数据失败:', error)
					this.resetStatistics()
				}
			}).catch(error => {
				console.error('获取设备统计数据失败:', error)
				this.resetStatistics()
			})
		},
		
		// 获取设备类型统计（由于后端未提供类型统计接口）
			getDeviceTypeStatistics() {
				// 这里使用大的size参数来获取足够的数据进行统计
				deviceApi.list({ size: 1000 }).then(res => {
					try {
						if (res && res.data) {
							const devices = res.data.records || res.data
							
							// 统计设备类型（支持字符串类型）
							const typeStats = {}
							devices.forEach(device => {
								const type = device.deviceType || '未知类型'
								typeStats[type] = (typeStats[type] || 0) + 1
							})
							this.deviceTypeList = Object.keys(typeStats).map(type => ({
								typeName: type, // 直接使用字符串类型名称
								count: typeStats[type],
								rate: ((typeStats[type] / this.deviceTotal) * 100).toFixed(2) + '%'
							}))
							
							// 更新图表
							this.updateDeviceTypeChart()
						}
					} catch (error) {
						console.error('处理设备类型统计失败:', error)
					}
				}).catch(error => {
					console.error('获取设备列表失败:', error)
				})
			},
		

			// 重置统计数据
				resetStatistics() {
				this.deviceTotal = 0
				this.deviceNormal = 0
				this.deviceMaintenance = 0
				this.deviceScrapped = 0
				this.deviceNormalRate = 0
				this.deviceMaintenanceRate = 0
				this.deviceScrappedRate = 0
			this.deviceTypeList = []
			this.deviceStatusList = []
			},

			// 获取设备列表
				getDeviceList() {
				deviceApi.list({
					page_num: this.current,
					size: this.size
				}).then(res => {
					if (res && res.data) {
							this.deviceList = res.data.records || []
							this.size = res.data.size || this.size
							this.current = res.data.current || this.current
							this.total = res.data.total || 0
							this.deviceTotal = res.data.total || 0 // 确保分页总数和统计总数一致
					} else {
						this.deviceList = []
						this.total = 0
					}
				}).catch(error => {
					console.error('获取设备列表失败:', error)
					this.deviceList = []
					this.total = 0
				})
			},

			// 初始化设备类型图表
			initDeviceTypeChart() {
				this.deviceTypeChart = this.$echarts.init(document.getElementById('deviceTypeChart'))
				this.updateDeviceTypeChart()
			},

			// 更新设备类型图表
			updateDeviceTypeChart() {
				if (!this.deviceTypeChart) return

				const option = {
					tooltip: {
						trigger: 'item',
						formatter: '{a} <br/>{b}: {c} ({d}%)'
					},
					legend: {
						data: this.deviceTypeList.map(item => item.typeName)
					},
					series: [
						{
							name: '设备类型',
							type: 'pie',
							radius: '55%',
							center: ['50%', '45%'],
							data: this.deviceTypeList.map(item => ({
								value: item.count,
								name: item.typeName
							})),
							emphasis: {
								itemStyle: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							}
						}
					]
				}

				this.deviceTypeChart.setOption(option)
			},

			// 初始化设备状态图表
			initDeviceStatusChart() {
				this.deviceStatusChart = this.$echarts.init(document.getElementById('deviceStatusChart'))
				this.updateDeviceStatusChart()
			},

			// 更新设备状态图表
			updateDeviceStatusChart() {
				if (!this.deviceStatusChart) return

				const option = {
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'shadow'
						}
					},
					xAxis: {
						data: this.deviceStatusList.map(item => item.statusName)
					},
					yAxis: {
						type: 'value'
					},
					series: [
								{
								data: this.deviceStatusList.map(item => ({
									value: item.count,
									itemStyle: {
										color: item.statusName === '正常' ? '#67c23a' : 
										      item.statusName === '维修' ? '#e6a23c' : 
										      '#f56c6c' // 报废状态颜色
										}
								})),
								type: 'bar',
								showBackground: true,
								backgroundStyle: {
									color: 'rgba(180, 180, 180, 0.2)'
								}
							}
					]
				}

				this.deviceStatusChart.setOption(option)
			}
		}
	}
</script>

<style scoped>
	.app-container {
		padding: 20px;
	}

	.card-container {
		margin-bottom: 0;
	}

	.card-header {
		font-size: 16px;
		font-weight: bold;
	}

	.card-box {
		display: flex;
		margin-bottom: 20px;
	}

	.box-card {
		margin-right: 20px;
		flex: 1;
	}

	.box-card:last-child {
		margin-right: 0;
	}

	.num-container {
		padding: 15px 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.num-font {
		font-size: 30px;
		font-weight: bold;
	}

	.green {
		color: #67c23a;
	}

	.red {
		color: #f56c6c;
	}

	.orange {
		color: #e6a23c;
	}

	.blue {
		color: #409eff;
	}

	.chart-container {
		margin-bottom: 20px;
	}

	.chart-card {
		height: 400px;
	}

	.chart-box {
		height: 350px;
		padding: 10px 0;
	}

	.chart {
		height: 320px;
	}

	.table-container {
		margin-bottom: 20px;
	}

	.table-card {
		overflow: hidden;
	}

	.el-pagination {
		margin-top: 20px;
		float: right;
	}
</style>